﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;

namespace JohnnySins.Code
{
    public class CheckEpochMember
    {
        protected static bool EpochApiEnabled
        {
            get
            {
                return GetFromWebConfig<bool>(ConfigurationManager.AppSettings, "EpochApiEnabled", false);
            }
        }

        protected static string EpochApiUsername
        {
            get
            {
                return GetFromWebConfig(ConfigurationManager.AppSettings, "EpochApiUsername", String.Empty);
            }
        }

        protected static string EpochApiPassword
        {
            get
            {
                return GetFromWebConfig(ConfigurationManager.AppSettings, "EpochApiPassword", String.Empty);
            }
        }  

        public static EpochAnswer CheckMember(string email)
        {
            EpochAnswer epoResult = new EpochAnswer();
            epoResult.IsActive = false;

            if (!EpochApiEnabled)
            {
                epoResult.IsActive = true;
                return epoResult;
            }

            string url = string.Format("https://epoch.com/services/customer_search?auth_user={0}&auth_pass={1}&email={2}&api_action=search", EpochApiUsername, EpochApiPassword, email);
            try
            {
                string result = RequestClient.Get(url);
                epoResult.Answer = result;

                if (result.Contains("<Status>Active Recurring"))
                {
                    epoResult.IsActive = true;
                    return epoResult;
                }

                if (result.Contains("<Status></Status>")
                    && result.Contains("<PasswordRemovalDate></PasswordRemovalDate>"))
                {
                    epoResult.IsActive = true;
                    return epoResult;
                }

                if (result.Contains("<Status>Cancelled Recurring"))
                {
                    int pos = result.IndexOf("<PasswordRemovalDate>");
                    if (pos < 0)
                        return epoResult;

                    result = result.Remove(0, pos + "<PasswordRemovalDate>".Length);
                    result = result.Substring(0, 10);

                    epoResult.IsActive = (DateTime.Parse(result) >= DateTime.Now.Date);
                    return epoResult;
                }
                else
                {
                    return epoResult;
                }
            }
            catch(Exception e)
            {
                epoResult.IsActive = false;
                epoResult.Error = e.Message;
                return epoResult;
            }
        }

        public static String PreparePOSTForm(string url, NameValueCollection data)
        {
            var sb = new StringBuilder();
            sb.Append("<html>");
            sb.AppendFormat("<body onload='document.forms[0].submit()'>");
            sb.AppendFormat("<form action='{0}' method='post'>", url);
            foreach (string key in data)
            {
                var str = data[key];
                sb.AppendFormat("<input type='hidden' name=" + key + " value=" + "'" + data[key] + "'" + ">");
            }
            sb.Append("</form>");
            sb.Append("</body>");
            sb.Append("</html>");

            return sb.ToString();
        }

        public static T GetFromWebConfig<T>(NameValueCollection section, string key, T defaultvalue)
        {
            T ret = defaultvalue;

            if (section != null && !String.IsNullOrEmpty(section[key]))
            {
                ret = (T)Convert.ChangeType(section[key], typeof(T));
            }

            return ret;
        }
    }

    public class EpochAnswer
    {
        public bool IsActive { get; set; }
        public string Answer { get; set; }
        public string Error { get; set; }

        public EpochAnswer()
        {
            IsActive = false;
            Answer = "";
            Error = "";
        }
    }
}